package com.giscloud.commons.utils;

import com.giscloud.commons.model.Server;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:giscloud
 * @Description:
 * @Date: 17:22 2020/3/24
 * @Modified By:
 */
public class NormalRoundRobin {
    private List<Server> servers;

    private int currentIndex;
    private int totalServer;

    public NormalRoundRobin(List<String> srs,Boolean normalRound) {
        servers = new ArrayList<>();
        for (String sr : srs) {
            Server server = new Server(sr);
            servers.add(server);
        }
        totalServer = servers.size();
        currentIndex = totalServer - 1;
    }


    public NormalRoundRobin(List<Server> servers) {
        this.servers = servers;
        totalServer = servers.size();
        currentIndex = totalServer - 1;
    }


    // 轮询
    public Server round() {
        currentIndex = (currentIndex + 1) % totalServer;
        return servers.get(currentIndex);
    }


    //public static void main(String[] args) {
    //    List servers = new ArrayList<>();
    //    servers.add(new Server("192.168.45.7:8768"));
    //    servers.add(new Server("192.168.45.8:8768"));
    //    servers.add(new Server("192.168.45.9:8767"));
    //    servers.add(new Server("192.168.45.10:8767"));
    //    NormalRoundRobin r = new NormalRoundRobin(servers);
    //    Server server = r.round();
    //    // 不带并发的轮询
    //    for (int i = 0; i < 14; i++) {
    //        System.out.println(r.round());
    //    }
    //
    //    System.out.println();
    //    System.out.println("==========================");
    //    System.out.println();
    //
    //    final CyclicBarrier b = new CyclicBarrier(14);
    //
    //    // 带并发的轮询
    //    for (int i = 0; i < 14; i++) {
    //        new Thread(new Runnable() {
    //            @Override
    //            public void run() {
    //                try {
    //                    b.await();
    //                    System.out.println(Thread.currentThread().getName() + " " + r.round());
    //                } catch (InterruptedException | BrokenBarrierException e) {
    //                    e.printStackTrace();
    //                }
    //            }
    //        }, "thread" + i).start();
    //    }
    //}

}
